import { Second } from "mvx-utils";
import { Send as fSend, Code, CodeError } from "mvx-foundation";
import { sleep } from "../sleep";
import { waitingRegistry } from "../ts";
export async function SendF(uri, requestF, resType, net, ...options) {
    let [ret, err] = await fSend(uri, await requestF(), resType, net, ...options);
    if (err == null) {
        return [ret, err];
    }
    if (err.code != Code.TokenExpire) {
        return [ret, err];
    }
    // 根据foundation的时序预定，出现此种情况，net已经恢复正常，则应该直接重试
    if (!net.is401()) {
        return await fSend(uri, await requestF(), resType, net, ...options);
    }
    let registry = waitingRegistry.get(net.getBaseUrl());
    if (registry === undefined) {
        return [ret, err];
    }
    return new Promise(resolve => {
        registry.push(err1 => {
            if (err1) {
                resolve([ret, err]);
                return;
            }
            let retry = async () => {
                resolve(await fSend(uri, await requestF(), resType, net, ...options));
            };
            retry().then();
        });
        sleep(60 * Second).then(() => {
            resolve([ret, new CodeError("time out")]);
        });
    });
}
export async function Send(uri, request, resType, net, ...options) {
    return (await SendF(uri, async () => { return request; }, resType, net, ...options));
}
